#include "chapter01.h"
#include "ColorSystem.h"
#include "text_utils.h"
#include "Battle.h"
#include "Bag.h"
#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;
using namespace TextUtils;

void initChapter01() {
    ColorSystem::changeTextColor('R');
    printWithDelay("===查尔斯的挽歌：地海回响===");
    cout << endl << endl << endl;
}

void text1_01() {
    ColorSystem::changeTextColor('Y');
    printWithDelay("海水撕裂岩壁，涌入“岩心礁”聚居区。刺耳的金属扭曲声和人群的惊叫声被洪流的怒吼淹没。");
    printWithDelay("查尔斯从冰冷的积水中挣扎起身，他的第一个念头不是恐惧，而是纯粹的愤怒——对这片试图吞噬他一切的土地的愤怒。", 8);

    cout << endl << endl;
    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （低声嘶吼，抹去脸上的污水）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“该死…又来了。安娜…闪闪！”");

    Sleep(2000);
    pressAnyKeyToContinue();
    clearScreen();

    // 显示目标更新
    ColorSystem::changeTextColor('G');
    printWithDelay("[目标更新] 在急速上涨的水位中，找到妻子安娜与女儿闪闪。");
    pressAnyKeyToContinue();
    clearScreen();
}

void processFracturedCorridor(Player& player) {
    ColorSystem::changeTextColor('Y');
    printWithDelay("【流程一：断裂的走廊】");
    printWithDelay("通往居住区的走廊已被撕裂，一道近三米宽的裂口横亘眼前，下方是翻滚着碎片的急流。", 8);
    cout << endl;

    // 环境观察选项
    while (true) {
        ColorSystem::changeTextColor('B');
        cout << "\n可调查的物品：" << endl;
        cout << "1. 墙上的应急灯" << endl;
        cout << "2. 水中的玩具" << endl;
        cout << "3. 尝试跨越裂缝" << endl;
        cout << "请选择：";

        int choice = getChoice(1, 3);
        clearScreen();

        if (choice == 1) {
            ColorSystem::changeTextColor('Y');
            printWithDelay("【环境观察：墙上的应急灯】");
            printWithDelay("应急灯闪烁不定，光线忽明忽暗。", 8);
            cout << endl;
            ColorSystem::changeTextColor('C');
            printWithDelay("查尔斯 （拍打灯罩，灯光稳定了片刻）：");
            ColorSystem::changeTextColor('W');
            printWithDelay("“连光都在死去。”");
        }
        else if (choice == 2) {
            ColorSystem::changeTextColor('Y');
            printWithDelay("【环境观察：水中的玩具】");
            printWithDelay("水中漂浮着一只破烂的机械鱼，看起来是个孩子的玩具。", 8);
            cout << endl;
            ColorSystem::changeTextColor('C');
            printWithDelay("查尔斯 （拾起，握紧）：");
            ColorSystem::changeTextColor('W');
            printWithDelay("“闪闪的…得快点。”");
        }
        else if (choice == 3) {
            // 敏捷检定：跨越裂缝
            ColorSystem::changeTextColor('Y');
            printWithDelay("【敏捷检定：跨越裂缝】", 8);
            cout << endl;

            if (checkStat(player.getAgility(), 12)) {
                ColorSystem::changeTextColor('G');
                printWithDelay("成功！");
                cout << endl;
                ColorSystem::changeTextColor('C');
                printWithDelay("查尔斯助跑跃过，落地翻滚卸力，起身毫不迟疑。");
                ColorSystem::changeTextColor('W');
                printWithDelay("“莉莉要是在，会夸我这下还算利落。”");
            }
            else {
                ColorSystem::changeTextColor('R');
                printWithDelay("失败！");
                cout << endl;
                ColorSystem::changeTextColor('C');
                printWithDelay("查尔斯险些滑落，勉强扒住边缘攀爬上来，生命值微损。");
                ColorSystem::changeTextColor('W');
                printWithDelay("“呃…！这副身体，到底还是不够强韧。”");
                player.takeDamage(5); // 受到轻微伤害
            }

            pressAnyKeyToContinue();
            clearScreen();

            // 落石判定1
            ColorSystem::changeTextColor('Y');
            printWithDelay("【落石判定1】", 8);
            printWithDelay("刚越过裂缝，头顶因震动落下碎石。", 8);
            cout << endl;
            ColorSystem::changeTextColor('C');
            printWithDelay("查尔斯：");
            ColorSystem::changeTextColor('W');
            printWithDelay("“啧！”");
            cout << endl;

            if (!checkStat(player.getAgility(), 10)) {
                ColorSystem::changeTextColor('R');
                printWithDelay("躲避失败！");
                cout << endl;
                player.takeDamage(8); // 受到轻微伤害
                // 添加流血Debuff
                player.addStatusEffect(StatusEffect(StatusEffect::BLEEDING, 3, 2));
            }
            else {
                ColorSystem::changeTextColor('G');
                printWithDelay("成功躲避了落石！");
            }

            pressAnyKeyToContinue();
            clearScreen();
            break; // 离开观察环节，继续流程
        }

        pressAnyKeyToContinue();
        clearScreen();
    }
}

// 处理地图交互事件（使用EventType枚举）
GameState processInteractiveEvent(Player& player, Map& map, EventType eventType) {
    clearScreen();
    switch (eventType) {
    case EventType::FRACTURED_CORRIDOR:  // 断裂的走廊
        processFracturedCorridor(player);
        break;
    case EventType::FIND_ANNA:  // 发现安娜
        processFindAnna(player);
        break;
    case EventType::RESCUE_SHANSHAN:  // 救援闪闪
        processRescueShanshan(player);
        break;
    case EventType::EVACUATION:  // 撤离点
        processEvacuation(player);
        return GameState::GAME_OVER;  // 章节结束
    default:
        printWithDelay("这里似乎没什么特别的...");
        pressAnyKeyToContinue();
    }
    map.displayMap();
    return GameState::EXPLORING;
}

//第一章地图交互
GameState handleExploringInput(Player& player, Map& map, char input) {
    switch (input) {
    case 'w': case 'W':
        map.movePlayer(Map::Direction::UP);
        break;
    case 's': case 'S':
        map.movePlayer(Map::Direction::DOWN);
        break;
    case 'a': case 'A':
        map.movePlayer(Map::Direction::LEFT);
        break;
    case 'd': case 'D':
        map.movePlayer(Map::Direction::RIGHT);
        break;
    case 'm': case 'M':
        return GameState::MENU;
    default:
        cout << "使用WASD移动，M打开菜单" << endl;
    }

    // 检查是否到达交互点
    int row, col;
    map.getPlayerPosition(row, col);
    if (map.isInteractive(row, col)) {
        // 将地图事件类型转换为EventType枚举
        EventType event = static_cast<EventType>(map.getInteractiveType(row, col));
        return processInteractiveEvent(player, map, event);
    }
    return GameState::EXPLORING;
}

/*
void runChapter01(Player& player) {
    initChapter01();
    text1_01();

    // 执行第一章各个流程
    processFracturedCorridor(player);
    processFindAnna(player);
    processRescueShanshan(player);
    processEvacuation(player);

    // 章节结束
    clearScreen();
    ColorSystem::changeTextColor('R');
    printWithDelay("=== 第一章：淹没之墟 结束 ===");
    cout << endl << endl;
    ColorSystem::changeTextColor('W');
    printWithDelay("查尔斯将安娜和闪闪安置在安全屋深处。");
    printWithDelay("他拿起装备，最后看了一眼来时的闸门。");
    printWithDelay("他手中紧握的，是莉莉炮身上脱落的一枚小小徽章。");
    printWithDelay("他的旅程，不再仅仅是为了回家，更添上了一层冰冷的复仇与对“力量”的迫切追寻。");

    pressAnyKeyToContinue();
}
*/

void runChapter01(Player& player, Map& map) {
   initChapter01();
   text1_01();

    // 加载第一章地图
    if (!map.loadMapFromFile(1)) {
        cerr << "警告：第一章地图加载失败！" << endl;
        return;
    }

    // 设置玩家初始位置（地图左上角）
    map.setPlayerPosition(1, 1);

    // 显示地图操作说明
    clearScreen();
    map.displayMap();
    cout << "使用WASD移动，M进入命令模式" << endl;
    pressAnyKeyToContinue();

    // 地图探索循环
    GameState state = GameState::EXPLORING;
    while (state != GameState::GAME_OVER) {
        clearScreen();
        map.displayMap();
 //       cout << "\n当前位置：";
        int row, col;
        map.getPlayerPosition(row, col);
 //       cout << "(" << row << "," << col << ")" << endl;

        if (state == GameState::EXPLORING) {
            cout << "输入移动方向(WASD)或M进入命令模式：";
            char input=_getch();
            state = handleExploringInput(player, map, input);
        }
        else if (state == GameState::MENU) {
            showMenu(player);
            string s; cin >> s;

            state = handleMenuInput(player, s, map);
        }
    }
}

void processFindAnna(Player& player) {
    ColorSystem::changeTextColor('Y');
    printWithDelay("【流程二：发现安娜】", 8);
    printWithDelay("在主厅，安娜被困在一张倾覆的金属实验桌下。水已没至她的胸口。", 8);
    printWithDelay("但她没有惊慌，而是以一种近乎冷酷的平静试图用念力移开重物，桌面因无形的力量微微震颤却无法挪开。", 8);
    printWithDelay("她的眼中闪烁着挫败与不甘。", 8);
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （冲上前，徒手试图抬起桌角）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“安娜！撑住！”");
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜 （声音冷静，甚至带着一丝责备）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“你的力量太慢了，查尔斯。蛮力解决不了问题。桌角第三号支点，最脆弱，用你的撬棍…如果你还带着的话。”");
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （依言操作，成功撬开缝隙）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“你总是…”");
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜 （打断他，被搀扶起来后立刻说）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“感性时间到此为止。我的腿暂时没用了，‘那个’在排斥我的神经信号。闪闪在里面的储藏室，门锁死了。");
    printWithDelay("钥匙在…（她指向墙上一个被水半淹的盒子）…但你需要密码。‘我们第一次见到莉莉的日子’。”");

    pressAnyKeyToContinue();
    clearScreen();

    // 智力/记忆检定：解锁密码盒
    ColorSystem::changeTextColor('Y');
    printWithDelay("【智力/记忆检定：解锁密码盒】", 8);
    cout << endl;

    //是不是很抽象还有中文变量
    bool 密码破解成功 = checkStat(player.getWisdom(), 10);

    if (密码破解成功) {
        ColorSystem::changeTextColor('G');
        printWithDelay("成功！");
        cout << endl;
        ColorSystem::changeTextColor('C');
        printWithDelay("查尔斯毫不犹豫输入日期。盒子打开。");
        ColorSystem::changeTextColor('W');
        printWithDelay("“我怎么可能忘记。那小家伙吵着要吃奶酪的日子。”");
    }
    else {
        ColorSystem::changeTextColor('R');
        printWithDelay("失败！");
        cout << endl;
        ColorSystem::changeTextColor('C');
        printWithDelay("查尔斯输入错误，盒子锁死。他低骂一声，只能用蛮力破坏盒子，获得钥匙但发出巨大噪音。");
    }

    pressAnyKeyToContinue();
    clearScreen();

    // 遇敌战斗：溺尸
    ColorSystem::changeTextColor('R');
    printWithDelay("【遇敌战斗】", 8);
    printWithDelay("破坏盒子的噪音或水流声吸引了敌人。几只被黑暗能量异化、形态扭曲的“溺尸”从水中爬出。它们曾是本地的居民。", 8);
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （拔出武器）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“…连安息都成了奢望。”");

    pressAnyKeyToContinue();
    clearScreen();

    // 战斗过程
    bool 战斗胜利 = battleWithDrowners(player);

    if (!战斗胜利) {
        // 如果战斗失败，游戏结束
        clearScreen();
        ColorSystem::changeTextColor('R');
        printWithDelay("你被溺尸击败了...");
        printWithDelay("游戏结束");
        exit(0);
    }

    clearScreen();
    ColorSystem::changeTextColor('M');
    printWithDelay("安娜：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“效率低下。它们的存在本身就是对能量的浪费。彻底净化掉。”");

    pressAnyKeyToContinue();
    clearScreen();
}

void processRescueShanshan(Player& player) {
    ColorSystem::changeTextColor('Y');
    printWithDelay("【流程三：救援闪闪】", 8);
    printWithDelay("用钥匙打开储藏室门。闪闪蜷缩在一个高架子上，海水已快淹到架子底部。", 8);
    printWithDelay("她怀里紧紧抱着一个破烂的老鼠玩偶，低声哭泣。", 8);
    cout << endl;

    ColorSystem::changeTextColor('P');
    printWithDelay("闪闪 （看到查尔斯，大哭）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“爸爸！水！水好可怕！娜娜不动了，莉莉也不在！我的娃娃要湿掉了！”");
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （涉水上前，声音放柔）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“闪闪，看着我。没事了，爸爸来了。跳下来，我接住你。”");
    cout << endl;

    ColorSystem::changeTextColor('P');
    printWithDelay("闪闪 （犹豫，抱紧玩偶）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“…你会接住我吗？像接住莉莉姐姐那样？”");
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“我保证。现在，跳！”");

    pressAnyKeyToContinue();
    clearScreen();

    // 魅力/安抚检定：鼓励闪闪跳下
    ColorSystem::changeTextColor('Y');
    printWithDelay("【魅力/安抚检定：鼓励闪闪跳下】", 8);
    cout << endl;

    // 使用幸运值作为安抚检定的依据
    bool 成功 = checkStat(player.getLuck(), 8);

    if (成功) {
        ColorSystem::changeTextColor('G');
        printWithDelay("成功！");
        cout << endl;
        ColorSystem::changeTextColor('Y');
        printWithDelay("闪闪跳入查尔斯怀中，被牢牢接住。");
    }
    else {
        ColorSystem::changeTextColor('R');
        printWithDelay("失败！");
        cout << endl;
        ColorSystem::changeTextColor('Y');
        printWithDelay("闪闪害怕不敢跳，查尔斯不得不爬上摇摇欲坠的架子抱她下来。");

        pressAnyKeyToContinue();
        clearScreen();

        // 额外的躲避检定
        ColorSystem::changeTextColor('Y');
        printWithDelay("【躲避检定】", 8);
        printWithDelay("架子倒塌了！", 8);
        cout << endl;

        if (!checkStat(player.getAgility(), 10)) {
            ColorSystem::changeTextColor('R');
            printWithDelay("躲避失败！");
            cout << endl;
            player.takeDamage(10); // 受到伤害
        }
        else {
            ColorSystem::changeTextColor('G');
            printWithDelay("成功避开了倒塌的架子！");
        }
    }

    pressAnyKeyToContinue();
    clearScreen();

    // 落石判定2
    ColorSystem::changeTextColor('Y');
    printWithDelay("【落石判定2】", 8);
    printWithDelay("抱着闪闪离开储藏室时，通道因结构损坏发生二次坍塌，更大的落石堵住来路。", 8);
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （护住闪闪）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“低头！”");
    cout << endl;

    // 幸运/敏捷检定
    bool 躲避成功 = checkStat((player.getLuck() + player.getAgility()) / 2, 12);

    if (!躲避成功) {
        ColorSystem::changeTextColor('R');
        printWithDelay("躲避失败！");
        cout << endl;
        ColorSystem::changeTextColor('Y');
        printWithDelay("查尔斯为保护闪闪而承受伤害，被落石砸中背部。");
        player.takeDamage(15); // 受到伤害
        // 添加受伤Debuff（这里用防御降低代替移动速度减缓）
        player.addStatusEffect(StatusEffect(StatusEffect::DEFENSE_BOOST, 5, -5));
    }
    else {
        ColorSystem::changeTextColor('G');
        printWithDelay("成功躲避了落石！");
    }

    pressAnyKeyToContinue();
    clearScreen();
}

void processEvacuation(Player& player) {
    ColorSystem::changeTextColor('Y');
    printWithDelay("【流程四：撤离与牺牲】", 8);
    printWithDelay("携带着安娜和闪闪，查尔斯按安娜指示的“最效率路径”撤离。", 8);
    printWithDelay("途经一个狭窄的维护通道入口时，一个熟悉的、急促尖细的声音从管道深处传来。", 8);
    cout << endl;

    ColorSystem::changeTextColor('B');
    printWithDelay("莉莉 （声音夹杂着电流杂音）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“查尔斯！这边！快！这条路还通！”");
    cout << endl;

    ColorSystem::changeTextColor('Y');
    printWithDelay("（一个约半米高、穿着改装工装的老鼠形机械体从阴影中冲出，她背着一具巨大的、几乎与她体型不符的旧世火炮，");
    printWithDelay("炮管还在微微发烫，显然刚清除了障碍。）");
    cout << endl;

    ColorSystem::changeTextColor('B');
    printWithDelay("莉莉：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“哎呀！查尔斯你受伤了！还有闪闪别怕！莉莉姐姐开路！”");
    cout << endl;

    ColorSystem::changeTextColor('Y');
    printWithDelay("一行人挤入通道。然而就在查尔斯和闪闪通过后，一次剧烈的震动导致通道结构变形，");
    printWithDelay("出口猛然收缩，将动作因瘫痪而迟缓的安娜和体型最小的莉莉卡在了后面。");
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜 （冷静地判断）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“通道要塌了。承载不了所有人。查尔斯，带闪闪走。这是最优解。”");
    cout << endl;

    ColorSystem::changeTextColor('B');
    printWithDelay("莉莉 （她的机械鼠尾焦急地摆动）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“不行！安娜姐姐不能留下！我…我个子小，我留下来撑住结构！我的炮能稳定一会儿！");
    printWithDelay("查尔斯，快带她们走！”");
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“莉莉！不行！”");
    cout << endl;

    ColorSystem::changeTextColor('B');
    printWithDelay("莉莉 （声音带着小女孩般的哭腔，但异常坚定）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“快走啊！你说过我是最勇敢的！让我做一次英雄！求你了！告诉闪闪…我下次再陪她玩娃娃…”");
    cout << endl;

    ColorSystem::changeTextColor('Y');
    printWithDelay("（莉莉用她的炮卡住变形的金属，为她最在乎的家人争取到宝贵的几秒钟。通道在她身后彻底坍塌。）");

    pressAnyKeyToContinue();
    clearScreen();

    // 安全屋
    ColorSystem::changeTextColor('Y');
    printWithDelay("【安全屋】", 8);
    printWithDelay("查尔斯强行带着哭泣的闪闪和沉默的安娜冲入安全屋，厚重的闸门在身后落下，");
    printWithDelay("隔绝了外面崩溃的世界和莉莉最后的信号杂音。寂静中，只有闪闪的抽泣声。", 8);
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜 （打破沉默，声音里没有悲伤，只有冰冷的决绝）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“情感是奢侈品，查尔斯。莉莉选择了最有价值的牺牲。她的数据…我会记住。但现在，黑暗消失了，这不是天灾。”");
    cout << endl;

    ColorSystem::changeTextColor('Y');
    printWithDelay("（她看向查尔斯受伤的手臂，示意他过来，用残存的微弱的能量灼烧伤口为其止血，过程冰冷且疼痛，但高效。）");
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“你必须回去。回到地表。找到‘黑暗’消失的源头，把它带回来，或者…找到能替代它的、更强大的力量。”");
    cout << endl;

    ColorSystem::changeTextColor('P');
    printWithDelay("闪闪 （抽噎着，看着爸爸处理伤口）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“莉莉姐姐…还能修好吗？她答应要陪我玩的…”");
    cout << endl;

    ColorSystem::changeTextColor('C');
    printWithDelay("查尔斯 （抱起女儿，声音沙哑）：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“…我不知道。” （他握紧了莉莉那枚小小的徽章。）");
    cout << endl;

    ColorSystem::changeTextColor('M');
    printWithDelay("安娜：");
    ColorSystem::changeTextColor('W');
    printWithDelay("“无论你找到什么，记住，力量才是唯一的答案，是生存的唯一依凭。忘记这个教训的代价，我们刚刚已经付过了。”");

    pressAnyKeyToContinue();
    clearScreen();
}

bool battleWithDrowners(Player& player) {
    // 创建溺尸敌人
    Monster drowner1("溺尸01", player.getLevel(), 60, 0, 8, 5, 3, 20);
    Monster drowner2("溺尸02", player.getLevel(), 50, 0, 7, 4, 2, 15);

    // 第一次战斗
    cout << "\n=== 遭遇了第一只溺尸！ ===" << endl;
    Battle battle1(&player, &drowner1);
    battle1.startBattle();

    if (!player.isAlive()) {
        return false;
    }

    // 第二次战斗
    cout << "\n=== 又一只溺尸出现了！ ===" << endl;
    Battle battle2(&player, &drowner2);
    battle2.startBattle();

    return player.isAlive();
}
